package com.lou.springboot.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
public class JdbcController {
    @Autowired
    JdbcTemplate jdbcTemplate;

    // 查询所有记录
    @GetMapping("/users/queryAll")
    public List<Map<String, Object>> queryAll(){
        List<Map<String, Object>> list = jdbcTemplate.queryForList("select * from tb_user");
        return list;
    }

    // 新增一条记录
    @PostMapping("/users/insert")
    public Object insert(String name, String password){
        if (StringUtils.isEmpty(name) || StringUtils.isEmpty(password))
            return "名称或密码为空";
        else {
            String sql = new String("insert into tb_user (`name`,`password`) values (\"%s\",\"%s\")");
            String finalSql = String.format(sql, name, password);
            jdbcTemplate.execute(finalSql);
            return true;
        }
    }
}
